//
//  CachalotAppDelegate.m
//  Cachalot
//
//  Created by Adam Cue on 3/29/11.
//  Copyright Adam Cue 2011.
//
//  This program is licensed and distributed under the terms of the GNU General Public License.  
//	The text for the license can be found in the license.txt file in this project.
//

#import "CachalotAppDelegate.h"

@implementation CachalotAppDelegate

@synthesize window;
@synthesize tabBar;

#pragma mark -
#pragma mark Application lifecycle

//Set up the tab bar and all the view controllers. Almost make the splash screen to display for 3 seconds before the normal screen shows.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
	tabBar = [[UITabBarController alloc] init];
    //pdfVC = [[PDFViewController alloc] init];
	megaVC = [[MegafaunaOfDayController alloc] init];
	UITabBarItem *mfodTab = [[[UITabBarItem alloc] initWithTitle:@"Megafauna" image:[UIImage imageNamed:@"dolphin_tab"] tag:0] autorelease];
	megaVC.tabBarItem = mfodTab;
	ReadingPickerViewController *readingVC = [[[ReadingPickerViewController alloc] init] autorelease];
	readingNavController = [[UINavigationController alloc] initWithRootViewController:readingVC];
	readingNavController.navigationBar.barStyle = UIBarStyleBlackOpaque;
	UITabBarItem *readingTab = [[[UITabBarItem alloc] initWithTitle:@"Readings" image:[UIImage imageNamed:@"readings_tab"] tag:0] autorelease];
	readingNavController.tabBarItem = readingTab;
	LessonPickerViewController *lessonVC = [[[LessonPickerViewController alloc] init] autorelease];
	lessonNavController = [[UINavigationController alloc] initWithRootViewController:lessonVC];
	lessonNavController.navigationBar.barStyle = UIBarStyleBlackOpaque;
	UITabBarItem *lessonTab = [[[UITabBarItem alloc] initWithTitle:@"Lessons" image:[UIImage imageNamed:@"lessons_tab"] tag:0] autorelease];
	lessonNavController.tabBarItem = lessonTab;
   SettingsViewController *settingsVC = [[[SettingsViewController alloc] init] autorelease];
	settingsNavController = [[UINavigationController alloc] initWithRootViewController:settingsVC];
	settingsNavController.navigationBar.barStyle = UIBarStyleBlackOpaque;
	UITabBarItem *settingsTab = [[[UITabBarItem alloc] initWithTitle:@"Settings" image:[UIImage imageNamed:@"settings-tab-button"] tag:0] autorelease];
	settingsNavController.tabBarItem = settingsTab;
	[tabBar setViewControllers:[NSArray arrayWithObjects:megaVC, readingNavController, lessonNavController, settingsNavController, nil]];
	//[tabBar setViewControllers:[NSArray arrayWithObjects:megaVC, nil]];
	[self.window addSubview:tabBar.view];
    [self.window makeKeyAndVisible];
	splashPage = [[SplashPageViewController alloc] initWithNibName:@"SplashPageViewController" bundle:nil];
	[window addSubview:splashPage.view];
	[window bringSubviewToFront:splashPage.view];
	[UIView animateWithDuration:0.5 delay:3.0 options:UIViewAnimationTransitionNone animations:^{splashPage.view.alpha = 0.0;} completion:^(BOOL completed){[splashPage.view removeFromSuperview]; [splashPage release];}];
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert)];
	return YES;
}

// Delegation methods
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)devToken {
	NSString *token = [devToken description];
	token = [token stringByReplacingOccurrencesOfString:@"<" withString:@""];
	token = [token stringByReplacingOccurrencesOfString:@">" withString:@""];
	token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://seamonster.ml.duke.edu/add_device?token=%@", token]]];
  [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:NULL];
	//NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	app.applicationIconBadgeNumber = 0;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	[connection release];
}

- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
    NSLog(@"Error in registration. Error: %@", err);
}

//Save CoreData context if the user presses home.
- (void)applicationWillResignActive:(UIApplication *)application {
	NSError *error;
	[[[MarineFetcher sharedInstance] managedObjectContext] save:&error];	
}

//Save the CoreData context if the app loses focus.
- (void)applicationDidEnterBackground:(UIApplication *)application{
	NSError *error;
	[[[MarineFetcher sharedInstance] managedObjectContext] save:&error];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive.
     */
}

//Save the CoreData context if the app is terminated.
- (void)applicationWillTerminate:(UIApplication *)application {
	NSError *error;
	[[[MarineFetcher sharedInstance] managedObjectContext] save:&error];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
   if(self.tabBar.selectedIndex == 0){
      [((MegafaunaOfDayController *)[self.tabBar.viewControllers objectAtIndex:self.tabBar.selectedIndex]) checkForNewMegafauna];
   }
   else{
      self.tabBar.selectedIndex = 0;
   }
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
	[tabBar release];
	[readingNavController release];
	[lessonNavController release];
   [settingsNavController release];
	[megaVC release];
	[splashPage release];
   [window release];
   [super dealloc];
}


@end